<!--
  功能：功能描述
  作者：Kevin
  邮箱：178676392@qq.com
  时间：2020年12月27日 22:07:23
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div>
    <el-row type="flex">
      <el-col :span="4">
        <span><b>商品分类列表</b></span>
      </el-col>
      <el-col :span="4">
        <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="禁用拖拽" class="right">
        </el-switch>
      </el-col>
      <el-col :span="4">
        <el-button type="danger" @click="deleteBatch" size="mini" round>批量删除</el-button>
        <el-button type="primary" v-if="draggable" @click="saveBatch" size="mini" round>批量保存</el-button>
      </el-col>
    </el-row>

    <el-row type="flex">
      <el-col :span="6">
        <el-tree :data="categories" show-checkbox :props="defaultProps" :expand-on-click-node="false" node-key="catId"
          :default-expanded-keys="expandedKey" :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop"
          ref="categoryTree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" size="mini" v-if="node.level <= 2" @click="() => append(data)">新增</el-button>
              <el-button type="text" size="mini" @click="() => edit(data)">修改</el-button>
              <el-button type="text" size="mini" v-if="node.childNodes.length == 0" @click="() => remove(node, data)">删除
              </el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
    </el-row>
    
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      draggable: false,
      title: '',
      dialogVisible: false,
      dialogType: '',
      category: {
        catId: null,
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: '',
        productUnit: ''
      },
      categories: [],
      expandedKey: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      pCid: [],
      maxLevel: 0,
      updateNodes: []
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    // 获取商品分类数据
    getDataList () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        // 将后台查询到的数据绑定到 categories 对象
        this.categories = data.data
      })
    },

    // 拖拽实现
    allowDrop (draggingNode, dropNode, type) {
      // 被拖动的当前节点以及所在的父节点总层数不能大于3
      // 被拖动当前节点的总层数
      this.nodeMaxLevel(draggingNode)
      // 当前正在拖动的节点 + 父节点所在的深度不大于3即可
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1
      if (type === 'inner') {
        return (deep + dropNode.level) <= 3
      } else {
        return (deep + dropNode.parent.level) <= 3
      }
    },
    nodeMaxLevel (node) {
      // 找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let index = 0; index < node.childNodes.length; index++) {
          if (node.childNodes[index].level > this.maxLevel) {
            this.maxLevel = node.childNodes[index].level
          }
          this.nodeMaxLevel(node.childNodes[index])
        }
      }
    },
    /**
     * draggingNode：被拖拽节点对应的 Node
     * dropNode：结束拖拽时最后进入的节点
     * dropType：被拖拽节点的放置位置（before、after、inner）
     * event：事件对象
     */
    handleDrop (draggingNode, dropNode, dropType, ev) {
      // 当前节点最新的父节点id
      let parentCid = 0
      let siblings = null
      if (dropType === 'before' || dropType === 'after') {
        parentCid = dropNode.parent.data.catId === undefined ? 0 : dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
      } else { // 'inner'
        parentCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      this.pCid.push(parentCid)
      // 当前节点最新的顺序
      for (let index = 0; index < siblings.length; index++) {
        // 如果遍历的是当前拖拽的节点，需要更新sort 和 parentCid
        if (siblings[index].data.catId === draggingNode.data.catId) {
          let catLevel = draggingNode.level
          if (siblings[index].level !== draggingNode.level) {
            // 当前节点层级发送变化
            catLevel = siblings[index].level
            // 修改子节点层级
            this.updateChildNodeLevel(siblings[index])
          }
          this.updateNodes.push({ catId: siblings[index].data.catId, sort: index, parentCid, catLevel })
        } else {
          // 兄弟节点
          this.updateNodes.push({ catId: siblings[index].data.catId, sort: index })
        }
      }
    },
    updateChildNodeLevel (node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let index = 0; index < node.childNodes.length; index++) {
          this.updateNodes.push({catId: node.childNodes[index].data.catId, catLevel: node.childNodes[index].level})
          this.updateChildNodeLevel(node.childNodes[index])
        }
      }
    },
    saveBatch () {
      // 将拖拽后的数据保存到数据库
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        // 弹出消息提示框
        this.$message({
          type: 'success',
          message: '调整商品分类保存成功!'
        })
        // 刷新页面数据
        this.getDataList()
        // 展开当前节点
        this.expandedKey = this.pCid
        // 清空值
        this.maxLevel = 0
        this.updateNodes = []
      })
    },

    // 添加商品分类数据
    append (data) {
      // 弹出 Dialog
      this.title = '新增商品分类信息'
      this.dialogVisible = true
      this.dialogType = 'add'
      // 设置商品分类属性
      this.category.parentCid = data.catId
      this.category.catLevel = parseInt(data.catLevel) + 1
      this.category.catId = null
      this.category.name = ''
      this.category.icon = ''
      this.category.productUnit = ''
      this.category.sort = 0
      this.category.showStatus = 1
    },
    // 保存商品分类数据到数据库
    addCategory () {
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        // 弹出消息提示框
        this.$message({
          type: 'success',
          message: '商品分类保存成功!'
        })
        // 关闭 Dialog
        this.dialogVisible = false
        // 刷新页面数据
        this.getDataList()
        // 展开当前节点
        this.expandedKey = [this.category.parentCid]
      })
    },

    // 修改商品分类数据
    edit (data) {
      this.title = '修改商品分类信息'
      this.dialogVisible = true
      this.dialogType = 'edit'

      // 发送请求，获取商品分类信息进行回显
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        this.category.catId = data.data.catId
        this.category.name = data.data.name
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
        this.category.parentCid = data.data.parentCid
      })
    },
    // 保存修改的商品分类数据
    updateCategory () {
      // 只修改商品分类的部分属性
      let { catId, name, icon, productUnit } = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({ catId, name, icon, productUnit }, false)
      }).then(({ data }) => {
        // 弹出消息提示框
        this.$message({
          type: 'success',
          message: '商品分类修改成功!'
        })
        // 关闭 Dialog
        this.dialogVisible = false
        // 刷新页面数据
        this.getDataList()
        // 展开当前节点
        this.expandedKey = [this.category.parentCid]
      })
    },

    saveCategory () {
      if (this.dialogType === 'add') {
        this.addCategory()
      } else if (this.dialogType === 'edit') {
        this.updateCategory()
      }
    },

    // 删除商品分类数据
    remove (node, data) {
      // 获取选中的商品分类的catId
      let ids = [data.catId]
      this.$confirm(`是否删除【${data.name}】商品分类?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          // 弹出消息提示框
          this.$message({
            type: 'success',
            message: '商品分类删除成功!'
          })
          // 刷新页面数据
          this.getDataList()
          // 展开当前节点
          this.expandedKey = [node.parent.data.catId]
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 批量删除
    deleteBatch () {
      let catIds = []
      let names = []
      // 获取被选中的所有节点
      let checkedNodes = this.$refs.categoryTree.getCheckedNodes()
      if (checkedNodes != null && checkedNodes.length > 0) {
        checkedNodes.forEach(node => {
          catIds.push(node.catId)
          names.push(node.name)
        })
        // 确认删除
        this.$confirm(`是否批量删除【${names}】商品分类?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            // 弹出消息提示框
            this.$message({
              type: 'success',
              message: '商品分类批量删除成功!'
            })
            // 刷新页面数据
            this.getDataList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message({
          message: '请至少选择一个商品分类进行删除!',
          type: 'warning'
        })
      }
    }

  },

  // 以下是生命周期钩子
  created () {
    this.getDataList()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.clearfix,
el-col {
  line-height: 32px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-row {
    margin-bottom: 20px;
}
</style>